<?php
/**
 * Created by PhpStorm.
 * User: 任旭明 <846723340@qq.com>
 * Date: 2018/10/26
 * Time: 15:13
 */

namespace app\model;


class WeChatModel
{


    /**
     * @var http请求 POST GET
     */
    static private function _curlHttp($url, $data = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if ($data) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /**
     * @var 获取微信用户信息
     */
    public function getUserInfo($reurl)
    {
        if (!isset($_GET['code'])) {
            $baseUrl = urlencode('http://' . $_SERVER['HTTP_HOST'] . '/activity_login?myurl='.$reurl);
            $url = config('wechat.AuthUrl') . 'connect/oauth2/authorize?appid=' . config('wechat.AppId') . '&redirect_uri=' . $baseUrl . '&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect';
            header('Location:' . $url);
            exit;
        } else {
            //获取code码，以获取openid和access_token                  
            $code = $_GET["code"];
            $myUrl = $_GET["myurl"];
            $result = $this->_getUserInfo($code);
            $result['url'] = $myUrl;
            return $result;
        }
    }

    /**
     * @var 获取用户信息操作
     */
    private function _getUserInfo($code)
    {
        // 获取token
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . config('wechat.AppId') . "&secret=" . config('wechat.AppSecret') . "&code=" . $code . "&grant_type=authorization_code";
        $result = $this->_curlHttp($url);
        $result = json_decode($result, true);
        // 用token 和openid 获取用户信息
        if (!empty($result['openid']) && !empty($result['access_token'])) {
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $result['access_token'] . "&openid=" . $result['openid'] . "&lang=zh_CN";
            $data['openid'] = $result['openid'];
            $data['access_token'] = $result['access_token'];
            $result = $this->_curlHttp($url, $data);
            return json_decode($result, true);
        }
    }
}